package org.patterns.behavior.command.calculator;

import java.util.ArrayDeque;
import java.util.Deque;

//计算器界面类：请求发送者
public class CalculatorForm {
    private AbstractCommand command;
    private final Deque<AbstractCommand> undoStack = new ArrayDeque<AbstractCommand>();
    private final Deque<AbstractCommand> redoStack = new ArrayDeque<AbstractCommand>();

    public void setCommand(AbstractCommand command) {
        this.command = command;
    }

    //调用命令对象的execute()方法执行运算
    public void compute(int value) {
        int i = command.execute(value);
        undoStack.push(command);
        System.out.println("执行运算，运算结果为：" + i);
    }

    //调用命令对象的undo()方法执行撤销
    public void undo() {
        if (undoStack.isEmpty()) {
            System.out.println("无法撤销：没有更多命令");
            return;
        }
        command = undoStack.pop();
        redoStack.push(command);
        int i = command.undo();
        System.out.println("执行撤销，运算结果为：" + i);
    }

    public void redo() {
        if (redoStack.isEmpty()) {
            System.out.println("无法恢复：没有更多命令");
            return;
        }
        command = redoStack.pop();
        undoStack.push(command);
        int i = command.redo();
        System.out.println("执行恢复，运算结果为：" + i);
    }

    public void save() {
        command.save();
        undoStack.clear();
        redoStack.clear();
        System.out.println("保存命令：" + command);
    }
}
